const fs = require('fs');
const path = require('path');
const db = require("../models");
const DAO = require("../dao/DAO");
const dayjs = require("dayjs");
const LoginLogs = db.models.loginLogs;

/** 登录日志 */
exports.login = (req, res) => {
    let pm = {
        page_size: req.body?.page_size ?? 10,
        current_page: req.body?.current_page || 1,
        params: {
            created_at: req.body?.created_at ? { [db.Op.between]: req.body?.created_at ?? '' } : '',
            status: req.body?.status ?? '',
        },
        include: [{
            model: db.models.users,
            attributes: ["id", "user_name"],
            where: req.body?.user_name ? { user_name: { [db.Op.substring]: req.body?.user_name ?? '' } } : {},
        }],
    }
    DAO.list(LoginLogs, pm, list => {
        res.sendResult(list)
    })
};
exports.deleteLogin = (req, res) => {
    let pm = req.body;
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    DAO.delete(LoginLogs, { id: pm.id }, data => {
        res.sendResult(data)
    })
}
/** 在线用户 */
exports.online = (req, res) => {
    let list = (Object.values(db.sseClient)).map(item => {
        const { clientList, ...row } = item;
        return row
    });
    // 查询所有的用户信息
    db.models.users.findAll({ where: { id: list.map(item => item.userId) }, raw: true, attributes: ["id", "user_name"] }).then(u => {
        list.forEach(i => { i.user_name = u.find(item => item.id == i.userId)?.user_name })
        res.sendResult({ data: list, code: 0, message: "操作成功！" })
    })
}

/** 系统日志 */
exports.system = (req, res) => {
    const logFilePath = path.resolve(process.cwd(), `logs`);
    // 获取文件夹下所有日志类型文件夹
    const files = fs.readdirSync(logFilePath);
    let list = {};
    files.forEach(file => {
        // 文件夹
        const stat = fs.statSync(path.join(logFilePath, file));
        if (stat.isDirectory()) {
            // 获取日志文件
            const subFiles = fs.readdirSync(path.join(logFilePath, file));
            list[file] = [];
            subFiles.forEach(subfile => {
                // 获取文件大小
                const size = fs.statSync(path.join(logFilePath, file, subfile)).size;
                list[file].push({
                    date: subfile.split('.')[1],
                    size: size
                });
            })
        }
    })
    // 排序
    Object.keys(list).sort().forEach(key => {
        list[key].sort((a, b) => { return +new Date(b.date) - +new Date(a.date) })
    })
    res.sendResult({ data: list, code: 0, message: "操作成功！" })
}
/** 日志详情 */
exports.systemDetail = (req, res) => {
    const { type, date } = req.body;
    if (!date || !type) return res.sendResult({ data: '', code: -1, message: "当前网络不稳定，请稍后重试" });
    const logFilePath = path.resolve(process.cwd(), `logs/${type}/${type}.${date}.log`);
    // 读取日志文件
    const log = fs.readFileSync(logFilePath, 'utf8');
    res.sendResult({ data: { log, name: `${type}.${date}.log` }, code: 0, message: "操作成功！" })
}
/** 删除系统日志 */
exports.deleteSystem = (req, res) => {
    const { type, date } = req.body;
    if (!date || !type) return res.sendResult({ data: '', code: -1, message: "当前网络不稳定，请稍后重试" });
    // 当天的日志不可删除
    if (date == dayjs(new Date()).format('yyyy-MM-dd')) return res.sendResult({ data: '', code: -1, message: "当天日志不可删除！" });
    const logFilePath = path.resolve(process.cwd(), `logs/${type}/${type}.${date}.log`);
    fs.unlinkSync(logFilePath);
    res.sendResult({ data: '', code: 0, message: "操作成功！" })
}

/** 操作日志 */
exports.operation = (req, res) => {
    let pm = {
        page_size: req.body?.page_size ?? 10,
        current_page: req.body?.current_page || 1,
        params: {
            request_time: req.body?.request_time ? { [db.Op.between]: req.body?.request_time ?? '' } : '',
        },
        attributes: ['id', 'status', 'api_path', 'method', 'ip_address', 'location', 'os', 'browser', 'duration', 'request_time'],
        include: [{
            model: db.models.users,
            attributes: ["id", "user_name"],
            where: req.body?.user_name ? { user_name: { [db.Op.substring]: req.body?.user_name ?? '' } } : {},
        }],
        order: [['request_time', 'DESC']],
    }
    DAO.list(db.models.opLogs, pm, list => {
        res.sendResult(list)
    })
}
/** 操作日志详情 */
exports.operationDetail = (req, res) => {
    let pm = { id: req.body?.id ?? '' }
    DAO.findOne(db.models.opLogs, pm, data => {
        res.sendResult(data)
    })
}